using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;

namespace Registration.Twitter
{
    public class TwitterParser
    {
        public static Tuple<Tweet[], Author[], Mention[]> LoadFile(string file)
        {
            return Load(File.ReadAllText(file));
        }

        public static Tuple<Tweet[], Author[], Mention[]> Load(string txt)
        {
            var tweets = new List<Tweet>();
            var mentions = new List<Mention>();
            var authors = new HashSet<Author>();
            Dictionary<String, Object> objects =
                (Dictionary<String, Object>) new JavaScriptSerializer().DeserializeObject(txt);
            var results = (Object[]) objects["results"];
            foreach (Dictionary<String, Object> tweet in results)
            {
                var author = new Author()
                                 {
                                     Author1 = ReadField(tweet, "from_user"),
                                     ImagePath = ReadField(tweet, "profile_image_url")
                                 };
                if (!authors.Add(author))
                {
                    author = authors.Where(a => a.Author1 == author.Author1).First();
                }

                var item = new Tweet()
                               {
                                   Author = ReadField(tweet, "from_user"),
                                   Author1 = author,
                                   TwitterID = ReadField(tweet, "id"),
                                   Tweet1 = ReadField(tweet, "text"),
                                   DateTime = DateTime.Parse((string) tweet["created_at"])
                               };
                if (item.Tweet1.Length > 160)
                {
                    Debug.Print(item.ToString());
                }
                mentions.AddRange(ExtractMentions(item));
                tweets.Add(item);
            }

            return new Tuple<Tweet[], Author[], Mention[]>(tweets.ToArray(), authors.ToArray(), mentions.ToArray());
        }

        private static string ReadField(Dictionary<string, object> tweet, string field)
        {
            return HttpUtility.HtmlDecode(tweet[field].ToString());
        }

        private static IEnumerable<Mention> ExtractMentions(Tweet item)
        {
            var mentions = new List<Mention>();
            Regex.Replace(item.Tweet1, @"\@[^\s,^:]+", s =>
                                                           {
                                                               mentions.Add(new Mention()
                                                                                {
                                                                                    AuthorMentioned =
                                                                                        s.ToString().Substring(1),
                                                                                    Tweet = item
                                                                                });
                                                               return "";
                                                           });
            return mentions;
        }
    }
}